package com.zzedu.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.bean.BeanUtils;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.common.utils.uuid.IdUtils;
import com.zzedu.domain.ZzFormFieldChangeLog;
import com.zzedu.domain.ZzOrganization;
import com.zzedu.dto.ZzFormFieldChangeLogDTO;
import com.zzedu.dto.ZzOrganizationDTO;
import com.zzedu.enmuns.FieldChangeRelationTypeEnum;
import com.zzedu.framework.transaction.ITransactionHandlerService;
import com.zzedu.service.IZzFormFieldChangeLogService;
import com.zzedu.service.IZzOrganizationService;
import com.zzedu.vo.ZzOrganizationVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构信息Controller
 *
 * @author Mr.Wang
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/agent/organization")
public class ZzOrganizationController extends BaseController {
    @Autowired
    private IZzOrganizationService zzOrganizationService;

    @Autowired
    private IZzFormFieldChangeLogService zzFormFieldChangeLogService;

    @Autowired
    private ITransactionHandlerService transactionHandlerService;

    /**
     * 查询机构信息列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:query')")
    @RequestMapping("/list")
    public TableDataInfo list(@RequestBody ZzOrganizationDTO zzOrganization) {

        IPage<ZzOrganization> page = zzOrganizationService.page(zzOrganization.getPageDTO(), zzOrganizationService.buildQuery(zzOrganization));
        return getDataTable(page, zzOrganizationService.convertVO(page.getRecords()));

    }

    /**
     * 导出机构信息列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:export')")
    @Log(title = "机构信息", businessType = BusinessType.EXPORT)
    @RequestMapping("/export")
    public void export(ZzOrganizationDTO zzOrganization) {
        List<ZzOrganization> list = zzOrganizationService.list(zzOrganizationService.buildQuery(zzOrganization));
        ExcelUtil<ZzOrganization> util = new ExcelUtil<ZzOrganization>(ZzOrganization.class);
        util.exportExcel(ServletUtils.getResponse(), list, "机构信息数据");
    }


    /**
     * 新增保存机构信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:add')")
    @Log(title = "机构信息", businessType = BusinessType.INSERT)
    @RequestMapping("/add")
    public AjaxResult addSave(@Validated @RequestBody ZzOrganizationDTO zzOrganizationDTO) {
        return toAjax(this.transactionHandlerService.runInTransaction(() -> {
            ZzOrganization zzOrganization = new ZzOrganization();
            BeanUtils.copyBeanProp(zzOrganization, zzOrganizationDTO);
            String[] provinceAndCityAndDistrict = zzOrganizationDTO.getProvinceAndCityAndDistrict();
            if (null != provinceAndCityAndDistrict) {
                zzOrganization.setProvince(provinceAndCityAndDistrict[0]);
                if (provinceAndCityAndDistrict.length > 1) {
                    zzOrganization.setCity(provinceAndCityAndDistrict[1]);
                }
                if (provinceAndCityAndDistrict.length > 2) {
                    zzOrganization.setDistrict(provinceAndCityAndDistrict[2]);
                }
            }
            if (CollectionUtils.isNotEmpty(zzOrganizationDTO.getLevel())) {
                zzOrganization.setLevel(JSON.toJSONString(zzOrganizationDTO.getLevel()));
            }
            zzOrganizationService.save(zzOrganization);
            saveFieldLog(zzOrganizationDTO, zzOrganization);
            return true;
        }));
    }


    /**
     * 获取机构信息详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:query')")
    @RequestMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        ZzOrganization zzOrganization = zzOrganizationService.getById(id);
        ZzOrganizationVO zzOrganizationVO = zzOrganizationService.convertVO(Lists.newArrayList(zzOrganization)).get(0);
        List<String> provinceAndCityAndDistrict = Lists.newArrayList(zzOrganization.getProvince(), zzOrganization.getCity(), zzOrganization.getDistrict());
        JSONObject jsonObject = (JSONObject) JSON.toJSON(zzOrganizationVO);
        jsonObject.put("provinceAndCityAndDistrict", provinceAndCityAndDistrict);
        jsonObject.remove("deleted");
        jsonObject.remove("gmtCreate");
        jsonObject.remove("gmtModify");
        jsonObject.remove("createBy");
        jsonObject.remove("updateBy");
        return success(jsonObject);

    }


    /**
     * 修改保存机构信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:edit')")
    @Log(title = "机构信息", businessType = BusinessType.UPDATE)
    @RequestMapping("/edit")
    public AjaxResult editSave(@Validated @RequestBody ZzOrganizationDTO zzOrganizationDTO) {
        return toAjax(this.transactionHandlerService.runInTransaction(() -> {
            ZzOrganization zzOrganization = new ZzOrganization();
            BeanUtils.copyBeanProp(zzOrganization, zzOrganizationDTO);
            String[] provinceAndCityAndDistrict = zzOrganizationDTO.getProvinceAndCityAndDistrict();
            if (null != provinceAndCityAndDistrict) {
                zzOrganization.setProvince(provinceAndCityAndDistrict[0]);
                if (provinceAndCityAndDistrict.length > 1) {
                    zzOrganization.setCity(provinceAndCityAndDistrict[1]);
                }
                if (provinceAndCityAndDistrict.length > 2) {
                    zzOrganization.setDistrict(provinceAndCityAndDistrict[2]);
                }
            }
            if (CollectionUtils.isNotEmpty(zzOrganizationDTO.getLevel())) {
                zzOrganization.setLevel(JSON.toJSONString(zzOrganizationDTO.getLevel()));
            }
            zzOrganizationService.updateById(zzOrganization);
            saveFieldLog(zzOrganizationDTO, zzOrganization);
            return true;
        }));
    }

    private void saveFieldLog(ZzOrganizationDTO zzOrganizationDTO, ZzOrganization zzOrganization) {
        if (CollectionUtils.isNotEmpty(zzOrganizationDTO.getZzFormFieldChangeLogDTOList())) {
            List<ZzFormFieldChangeLogDTO> zzFormFieldChangeLogDTOList = zzOrganizationDTO.getZzFormFieldChangeLogDTOList();
            LocalDateTime busDate = LocalDateTime.now();
            String batchNo = IdUtils.fastSimpleUUID();
            zzFormFieldChangeLogService.saveBatch(zzFormFieldChangeLogDTOList.stream().map(zzFormFieldChangeLogDTO -> {
                ZzFormFieldChangeLog zzFormFieldChangeLog = new ZzFormFieldChangeLog();
                zzFormFieldChangeLog.setRelationId(zzOrganization.getId());
                zzFormFieldChangeLog.setBusDate(busDate);
                zzFormFieldChangeLog.setRelationType(FieldChangeRelationTypeEnum.ORG.getCode());
                zzFormFieldChangeLog.setBatchNo(batchNo);
                zzFormFieldChangeLog.setField(zzFormFieldChangeLogDTO.getField());
                zzFormFieldChangeLog.setFieldCode(zzFormFieldChangeLogDTO.getFieldCode());
                zzFormFieldChangeLog.setNewValue(zzFormFieldChangeLogDTO.getNewValue());
                zzFormFieldChangeLog.setOldValue(zzFormFieldChangeLogDTO.getOldValue());
                zzFormFieldChangeLog.setOperAccNo(SecurityUtils.getLoginUser().getUsername());
                zzFormFieldChangeLog.setOperName(SecurityUtils.getSysUser().getNickName());
                return zzFormFieldChangeLog;
            }).collect(Collectors.toList()));
        }
    }

    /**
     * 删除机构信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('agent:organization:remove')")
    @Log(title = "机构信息", businessType = BusinessType.DELETE)
    @RequestMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(zzOrganizationService.removeBatchByIds(ids));
    }
}
